package cn.micro.system.manage.service.impl;

import cn.micro.system.manage.common.exception.SystemException;
import cn.micro.system.manage.common.utils.MenuHelper;
import cn.micro.system.manage.common.utils.RouterHelper;
import cn.micro.system.manage.entity.SysDimMenu;
import cn.micro.system.manage.entity.SysDimRole;
import cn.micro.system.manage.entity.SysDimRoleMenu;
import cn.micro.system.manage.entity.vo.AssginMenuVo;
import cn.micro.system.manage.entity.vo.RouterVo;
import cn.micro.system.manage.mapper.SysDimMenuMapper;
import cn.micro.system.manage.mapper.SysDimRoleMenuMapper;
import cn.micro.system.manage.service.SysDimMenuService;
import cn.micro.system.manage.service.SysDimRoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author wr
 * @since 2023-12-25
 */
@Service
public class SysDimMenuServiceImpl extends ServiceImpl<SysDimMenuMapper, SysDimMenu> implements SysDimMenuService {

    @Resource
    private SysDimRoleMenuMapper sysDimRoleMenuMapper;

    //菜单列表（树形）
    @Override
    public List<SysDimMenu> findNodes() {
        //获取所有菜单
        List<SysDimMenu> sysMenuList = baseMapper.selectList(null);
        //所有菜单数据转换要求数据格式
        List<SysDimMenu> resultList = MenuHelper.bulidTree(sysMenuList);
        return resultList;
    }

    //删除菜单
    @Override
    public void removeMenuById(String id) {
        //查询当前删除菜单下面是否子菜单
        //根据id = parentid
        QueryWrapper<SysDimMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        if(count > 0) {//有子菜单
            throw new SystemException(201,"请先删除子菜单");
        }
        //调用删除
        baseMapper.deleteById(id);
    }

    //根据角色分配菜单
    @Override
    public List<SysDimMenu> findMenuByRoleId(String roleId) {
        //获取所有菜单 status=1
        QueryWrapper<SysDimMenu> wrapperMenu = new QueryWrapper<>();
        wrapperMenu.eq("status",1);
        List<SysDimMenu> menuList = baseMapper.selectList(wrapperMenu);

        //根据角色id查询 角色分配过的菜单列表
        QueryWrapper<SysDimRoleMenu> wrapperRoleMenu = new QueryWrapper<>();
        wrapperRoleMenu.eq("role_id",roleId);
        List<SysDimRoleMenu> roleMenus = sysDimRoleMenuMapper.selectList(wrapperRoleMenu);

        //从第二步查询列表中，获取角色分配所有菜单id
        List<String> roleMenuIds = new ArrayList<>();
        for (SysDimRoleMenu sysRoleMenu:roleMenus) {
            String menuId = String.valueOf(sysRoleMenu.getMenuId());
            roleMenuIds.add(menuId);
        }

        //数据处理：isSelect 如果菜单选中 true，否则false
        // 拿着分配菜单id 和 所有菜单比对，有相同的，让isSelect值true
        for (SysDimMenu sysMenu:menuList) {
            if(roleMenuIds.contains(sysMenu.getId())) {
                sysMenu.setSelect(true);
            } else {
                sysMenu.setSelect(false);
            }
        }

        //转换成树形结构为了最终显示 MenuHelper方法实现
        List<SysDimMenu> sysMenus = MenuHelper.bulidTree(menuList);
        return sysMenus;
    }

    //给角色分配菜单权限
    @Override
    @Transactional
    public void doAssign(AssginMenuVo assginMenuVo) {
        //根据角色id删除菜单权限
        QueryWrapper<SysDimRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",assginMenuVo.getRoleId());
        sysDimRoleMenuMapper.delete(wrapper);
        //遍历菜单id列表，一个一个进行添加
        List<String> menuIdList = assginMenuVo.getMenuIdList();
        for (String menuId:menuIdList) {
            SysDimRoleMenu sysRoleMenu = new SysDimRoleMenu();
            sysRoleMenu.setMenuId(Long.parseLong(menuId));
            sysRoleMenu.setRoleId(Long.parseLong(assginMenuVo.getRoleId()));
            sysDimRoleMenuMapper.insert(sysRoleMenu);
        }
    }

    //根据userid查询菜单权限值
    @Override
    public List<RouterVo> getUserMenuList(String userId) {
        //admin是超级管理员，操作所有内容
        List<SysDimMenu> sysMenuList = this.baseMapper.findMenuListUserId(userId);;
        //判断userid值是1代表超级管理员，查询所有权限数据
//        if("1".equals(userId)) {
//            QueryWrapper<SysDimMenu> wrapper = new QueryWrapper<>();
//            wrapper.eq("status",1);
//            wrapper.orderByAsc("sort_value");
//            sysMenuList = baseMapper.selectList(wrapper);
//        } else {
//            //如果userid不是1，其他类型用户，查询这个用户权限
//            sysMenuList = baseMapper.findMenuListUserId(userId);
//        }
        //构建是树形结构
        List<SysDimMenu> sysMenuTreeList = MenuHelper.bulidTree(sysMenuList);
        //转换成前端路由要求格式数据
        List<RouterVo> routerVoList = RouterHelper.buildRouters(sysMenuTreeList);
        return routerVoList;
    }

    //根据userid查询按钮权限值
    @Override
    public List<String> getUserButtonList(String userId) {
        List<SysDimMenu> sysMenuList = baseMapper.findMenuListUserId(userId);
        //判断是否管理员
//        if("1".equals(userId)) {
//            sysMenuList =
//                    baseMapper.selectList(new QueryWrapper<SysDimMenu>().eq("status",1));
//        } else {
//            sysMenuList = baseMapper.findMenuListUserId(userId);
//        }
        //sysMenuList遍历
        List<String> permissionList = new ArrayList<>();
        for (SysDimMenu sysMenu:sysMenuList) {
            // type=2
            if(sysMenu.getType()==2) {
                String perms = sysMenu.getPerms();
                permissionList.add(perms);
            }
        }
        return permissionList;
    }

    @Override
    public List<SysDimMenu> getByName(SysDimMenu sysDimMenu) {
        LambdaQueryWrapper<SysDimMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(sysDimMenu.getName()),SysDimMenu::getName,sysDimMenu.getName())
                .eq(sysDimMenu.getParentId()!=null,SysDimMenu::getParentId,sysDimMenu.getParentId())
                .ne(StringUtils.isNotEmpty(sysDimMenu.getId()),SysDimMenu::getId,sysDimMenu.getId());
        return this.baseMapper.selectList(queryWrapper);
    }
}
